#
# cifar10_t01.py - ok
#
###############################################################################
#
import time
import torch
import torchvision
import matplotlib.pyplot as plt
from torch.utils.data import DataLoader
import cifar10

CIFAR10_ROOT = cifar10.ROOT

# 定义超参数
LR = 0.01           # 学习率
EPOCHS = 30         # 轮次
BATCH_SIZE = 64     # 批次大小
DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")


# cifar10 分类索引
classes = ('plane', 'car', 'bird', 'cat', 'deer',
           'dog', 'frog', 'horse', 'ship', 'truck')
#
# 3. 据集的准备及加载
#
# 训练数据
train_data = cifar10.get_dataset(
    CIFAR10_ROOT, train=True, transform=torchvision.transforms.ToTensor())
train_loader = DataLoader(
    dataset=train_data, batch_size=BATCH_SIZE, shuffle=True)

# 测试数据
test_data = cifar10.get_dataset(
    CIFAR10_ROOT, train=False, transform=torchvision.transforms.ToTensor())
test_loader = DataLoader(
    dataset=test_data, batch_size=BATCH_SIZE, shuffle=True)

train_data_size = len(train_data)
test_data_size = len(test_data)

print(f"训练数据集的长度为 {train_data_size}")
print("测试数据集的长度为 {}".format(test_data_size))
# print(train_data.data.shape)    # (I, H, W, C) = (50000, 32, 32, 3)


#
# 4. 神经网络、损失函数、优化器等加载
#
net = cifar10.Net()
net = net.to(DEVICE)

# 损失函数
criterion = torch.nn.CrossEntropyLoss()
criterion = criterion.to(DEVICE)

# 优化器
optimizer = torch.optim.SGD(net.parameters(), lr=LR)

# 开始训练
start_time = time.time()
for epoch in range(EPOCHS):
    print(f"第 {epoch+1} 轮训练开始...")
    # 训练步骤开始
    net.train()
    for step, data in enumerate(train_loader, 0):
        imgs, targets = data
        imgs = torch.Tensor(imgs).to(DEVICE)
        targets = torch.Tensor(targets).to(DEVICE)

        output = net(imgs)
        loss = criterion(output, targets)

        # 优化器优化模型
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if step % 100 == 99:
            t = time.time() - start_time
            print('[%2d,%5d] Loss: %.3f Elapsed: %f' %
                  (epoch + 1, step + 1, loss.item(), t))

    # 评估步骤开始
    net.eval()
    total_accuracy = 0
    total_test_loss = 0
    with torch.no_grad():
        for (imgs, targets) in test_loader:
            # imgs, targets = data
            imgs = torch.Tensor(imgs).to(DEVICE)
            targets = torch.Tensor(targets).to(DEVICE)

            outputs = net(imgs)
            loss = criterion(outputs, targets)

            total_test_loss += loss.item()
            accuracy = (outputs.argmax(1) == targets).sum()
            total_accuracy += accuracy
        # endfor
    # endwith
    print("整体测试集上的 Loss: {}".format(total_test_loss))
    print("整体测试集上的 Accuracy: {}".format(total_accuracy/test_data_size))
    # total_test_step += 1

    # torch.save(model, "test_{}.pth".format(i))
    # print("模型已保存")

# writer.close()

    # # 每300个样本输出一下结果
    # if step % 300 == 299:
    #     print('[%d,%5d] loss: %.3f' %   #
    #           (epoch + 1, step + 1, running_loss / 300))


#
def my_test_00():
    train_loader_iter = iter(train_loader)
    x, y = next(train_loader_iter)  # [64, 3, 32, 32]
    # pooling = torch.nn.MaxPool2d(2)
    # x1 = pooling(x)

    xmodel = torch.nn.Sequential(
        # [64, 3, 32, 32] => [64, 32, 32, 32]
        torch.nn.Conv2d(3, 32, 5, padding=2),
        # [64, 32, 32, 32] => [64, 32, 16, 16]
        torch.nn.MaxPool2d(2),
        # [64, 32, 16, 16] => [64, 32, 16, 16]
        torch.nn.Conv2d(32, 32, 5, padding=2),
        # [64, 32, 16, 16] => [64, 32, 8, 8]
        torch.nn.MaxPool2d(2),
        # [64, 32, 8, 8] => [64, 64, 8, 8]
        torch.nn.Conv2d(32, 64, 5, padding=2),
        # [64, 64, 8, 8] => [64, 64, 4, 4]
        torch.nn.MaxPool2d(2),
        # [64, 64, 4, 4] => [64, 1024]
        torch.nn.Flatten(),
        # [64, 1024] => [64, 64]
        torch.nn.Linear(1024, 64),
        # [64, 64] => [64, 10]
        torch.nn.Linear(64, 10)
    )

    x = xmodel(x)  # [64, 10]
    pass

# my_test_00()


def my_test_01():
    """
    测试 to(DEVICE)
    """
    train_loader_iter = iter(train_loader)
    x, y = next(train_loader_iter)  # [64, 3, 32, 32]

    x = torch.Tensor(x).to(DEVICE)
    y = torch.Tensor(y).to(DEVICE)

    output = net(x)
    loss = criterion(output, y)

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    pass


# my_test_01()
